package com.simonall.print;

import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.OrientationRequested;

import com.simonall.enums.FileExtenNameEnum;

/**
 * 通用打印机，打印选项对话框
 * 
 * @author simonall
 */
public class SimpleManualPrintHandler implements PrintHandler {

	private DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
	
	@Override
	public FileExtenNameEnum[] handleType() {
		return new FileExtenNameEnum[] {}; // 不支持通配
	}

	public void print(byte[] bytes, Integer copies) throws Exception {
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		PrintService printService[] = PrintServiceLookup.lookupPrintServices(null, null);
		PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
		PrintService service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, pras);
		if (service != null) {
			print(bytes, service, copies);
		}
	}

	@Override
	public void print(byte[] bytes, PrintService service, Integer copies) throws Exception {
		DocPrintJob printJob = service.createPrintJob();
		DocAttributeSet docas = new HashDocAttributeSet();
		docas.add(OrientationRequested.PORTRAIT);
		Doc doc = new SimpleDoc(bytes, flavor, docas);
		
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		pras.add(new Copies(copies));
		printJob.print(doc, pras);
	}

	@Override
	public void print(InputStream input, PrintService service, Integer copies) throws Exception {
		byte[] bytes = new byte[input.available()];
		input.read(bytes);
		print(bytes, service, copies);
	}

}
